﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace DingTalkAgent.Web.Controllers
{
    [Common.Filter.AuthorizeFilter]
    public class DictionaryController : Common.adminBaseController
    {
        private DingTalkAgent.SqlData.Dictionary IDictionary = new SqlData.Dictionary();

        //获取列表信息
        [Common.Filter.ViewPage]
        public ActionResult List(int PageIndex = 1)
        {
            try
            {
                int records = 0;
                if (Request.IsAjaxRequest())
                {
                    int rows = Convert.ToInt32(Request["rows"] == null ? "10" : Request["rows"].ToString());
                    int page = Convert.ToInt32(Request["page"] == null ? "1" : Request["page"].ToString());
                    var keyword = Request["keyword"] == null ? "" : Request["keyword"].ToString();

                    int Parent_ID = Request.Form["Parent_ID"] == null|Request.Form["Parent_ID"].ToString() == "j1_1" ? 0 : Convert.ToInt32(Request.Form["Parent_ID"].ToString());

                    List<DingTalkAgent.Model.Dictionary> list = IDictionary.GetPageList(page, rows, out records, Parent_ID, keyword);
                    var pagelist = new Models.Dict_Page()
                    {
                        records = records,
                        page = page,
                        pagesize = rows,
                        List = list,                      
                    };

                      return Json(pagelist);
                }

                return View();
            }
            catch (Exception ex)
            {
                //错误日志
                Models.ErrorLog.Add(_view_Admin_Info.UserID, "/Dictionary/List", ex.Message, _view_Admin_Info.Name, "");
                return Content(ConfigHelper.getErrorMsg);
            }
        }
        //获取组织结构，公共信息
        [Common.myCommon]
        public ActionResult GetJsonList(string Code = "001")
        {
            try
            {
                List<DingTalkAgent.Model.Dictionary> list = IDictionary.IEnumGetList("").ToList();
                var m = new DingTalkAgent.Model.Dictionary() { id = 0, text = "字典结构", Parent_ID = -1 };
                buildTree(list, m, 0);
                var l = new List<DingTalkAgent.Model.Dictionary>() { m };
                return Json(l,JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                //错误日志
                Models.ErrorLog.Add(_view_Admin_Info.UserID, "/Department/GetJsonList", ex.Message, _view_Admin_Info.Name, "");
                return Content(ConfigHelper.getErrorMsg);
            }
        }

        //获取组织结构，公共信息
        [Common.myCommon]
        public ActionResult GetJsonListCommon(int Parent_ID = -1, string id = "")
        {
            try
            {
                List<DingTalkAgent.Model.Dictionary> list = IDictionary.IEnumGetList(" Parent_ID = " + Parent_ID).ToList();
                var m = new DingTalkAgent.Model.Dictionary() { id = 0, text = "所有", Parent_ID = -1 };
                buildTree(list, m, Parent_ID, "," + id);
                var l = new List<DingTalkAgent.Model.Dictionary>() { m };
                return Json(l);
            }
            catch (Exception ex)
            {
                //错误日志
                Models.ErrorLog.Add(_view_Admin_Info.UserID, "/Department/GetJsonList", ex.Message, _view_Admin_Info.Name, "");
                return Content(ConfigHelper.getErrorMsg);
            }
        }

        //添加信息
        public ActionResult Add(int Parent_ID)
        {
            DingTalkAgent.Model.Dictionary m = new Model.Dictionary();
            if (Parent_ID == 0)
            {
                m.ParentName = "字典结构";

            }
            else
            {
                m.ParentName = IDictionary.GetModel(Parent_ID).Name;
                m.Parent_ID = Parent_ID;

            }
            return View(m);
        }
        [HttpPost]
        public ActionResult Add(DingTalkAgent.Model.Dictionary model)
        {
            try
            {
                if (IDictionary.Add(model) > 0)
                {
                    //操作记录
                    Models.Operation.Add(_view_Admin_Info.UserID.ToString(), "添加Dictionary", "成功添加Dictionary:", _view_Admin_Info.Name, "");
                    return Content("true");
                }
                else
                {
                    return Content("保存信息失败!");
                }

            }
            catch (Exception ex)
            {
                //错误日志
                Models.ErrorLog.Add(_view_Admin_Info.UserID, "/Dictionary/Add", ex.Message, _view_Admin_Info.Name, "");
                return Content(ConfigHelper.getErrorMsg);
            }

        }
        //修改信息
        public ActionResult Edit(int id)
        {

            try
            {
                var m = IDictionary.GetModel(id);
                if (m.Parent_ID == 0)
                {
                    m.ParentName = "字典结构";
                }
                else
                {
                    m.ParentName = IDictionary.GetModel(m.Parent_ID).Name;
                }

                return View(m);
            }
            catch (Exception ex)
            {
                //错误日志
                Models.ErrorLog.Add(_view_Admin_Info.UserID, "/Dictionary/Edit", ex.Message, _view_Admin_Info.Name, "");
                ViewBag.Msg = "查找的信息不存在!";
                return View("Error");
            }
        }

        [HttpPost]
        public ActionResult Edit(DingTalkAgent.Model.Dictionary model)
        {
            try
            {
                if (IDictionary.Update(model))
                {
                    //操作记录
                    Models.Operation.Add(_view_Admin_Info.UserID.ToString(), "修改Dictionary", "成功修改Dictionary:", _view_Admin_Info.Name, "");
                    return Content("true");
                }
                else
                {
                    return Content("保存信息失败！");
                }
            }
            catch (Exception ex)
            {
                //错误日志
                Models.ErrorLog.Add(_view_Admin_Info.UserID, "/Dictionary/Edit", ex.Message, _view_Admin_Info.Name, "");
                return Content(ConfigHelper.getErrorMsg);
            }
        }
        //删除信息
        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                if (IDictionary.Delete(id))
                {
                    //操作记录
                    Models.Operation.Add(_view_Admin_Info.UserID.ToString(), "删除Dictionary", "成功删除Dictionary:id:" + id, _view_Admin_Info.Name, "");
                    return Content("true");
                }
                else
                {
                    return Content("删除信息失败!");
                }

            }
            catch (Exception ex)
            {
                //错误日志
                Models.ErrorLog.Add(_view_Admin_Info.UserID, "/Dictionary/Delete", ex.Message, _view_Admin_Info.Name, "");
                return Content(ConfigHelper.getErrorMsg);
            }
        }

        //删除多个信息
        [HttpPost]
        public ActionResult Deletes(string ids)
        {
            try
            {
                //
                ids = Discuz.Common.Utils.ChkSQL(ids).TrimEnd(',');
                if (IDictionary.Deletes(ids))
                {
                    //操作记录
                    Models.Operation.Add(_view_Admin_Info.UserID.ToString(), "批量删除Dictionary", "成功批量删除Dictionary:ids:" + ids, _view_Admin_Info.Name, "");
                    return Content("true");
                }
                else
                {
                    return Content("删除信息失败!");
                }

            }
            catch (Exception ex)
            {
                //错误日志
                Models.ErrorLog.Add(_view_Admin_Info.UserID, "/Dictionary/Deletes", ex.Message, _view_Admin_Info.Name, "");
                return Content(ConfigHelper.getErrorMsg);
            }
        }


        #region 辅助方法
        //递归树
        private void buildTree(List<DingTalkAgent.Model.Dictionary> list, DingTalkAgent.Model.Dictionary model, int parentID, string ids = "")
        {
            var l = list.Where(m => m.Parent_ID == parentID).ToList();
            if (model.Parent_ID == 0 && l.Count() > 0)
            {
                model.state = "closed";
            }
            foreach (var m in l)
            {
                buildTree(list, m, m.Dic_ID, ids);
            }
            if (ids.Contains("," + model.Dic_ID + ","))
            {
                model.@checked = true;
            }
            model.children = l;
        }
        #endregion
    }
}

